package com.example.spring_data_jpa.service;

import com.example.spring_data_jpa.entity.User;
import com.example.spring_data_jpa.repository.SpecificationUserRepository;
import com.example.spring_data_jpa.repository.UserHqlRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private SpecificationUserRepository userRepository;
    @Autowired
    private UserHqlRepository hqlRepository;

    public List<User> selectUser(String name,String city){
        List<User> all = userRepository.findAll(((root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasLength(name)) {
                list.add(criteriaBuilder.equal(root.get("name"), name));
            }
            if (StringUtils.hasLength(city)) {
                list.add(criteriaBuilder.like(root.get("city"), "%" + city + "%"));
            }
            Predicate[] array = list.toArray(new Predicate[0]);
            query.orderBy(criteriaBuilder.desc(root.get("name")));
            return criteriaBuilder.and(array);
        }));
        return all;
    }

    @Transactional
    public User getAndUpdate(Integer id){
        User byId = hqlRepository.findById(2);
        //在事务中可以通过直接设置属性值来更新
        byId.setCity("苏州");
        return byId;
    }

    @Transactional
    public  List<User> getAndUpdateUserList(){
        List<User> all = userRepository.findAll();
        all.forEach(user -> {
            user.setName(user.getName()+"_edit");
        });
        return all;
    }

}
